package org.jeecg.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.collections.CollectionUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.entity.*;
import org.jeecg.modules.entity.vo.CusStatisticsVo;
import org.jeecg.modules.entity.vo.DbPurposeVo;
import org.jeecg.modules.entity.vo.PurposeStatisticsVo;
import org.jeecg.modules.mapper.DbFileMapper;
import org.jeecg.modules.mapper.DbPurposeMapper;
import org.jeecg.modules.service.IDbFileService;
import org.jeecg.modules.service.IDbPurposeFollowUpService;
import org.jeecg.modules.service.IDbPurposeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: db_purpose
 * @Author: jeecg-boot
 * @Date:   2024-06-13
 * @Version: V1.0
 */
@Service
public class DbPurposeServiceImpl extends ServiceImpl<DbPurposeMapper, DbPurpose> implements IDbPurposeService {

    @Autowired
    private DbPurposeMapper dbPurposeMapper;
    @Autowired
    private IDbFileService dbFileService;
    @Autowired
    private IDbPurposeFollowUpService dbPurposeFollowUpService;
    /**
     * 添加
     * @param dbPurpose
     * @return
     */
    @Transactional
    public void add(DbPurpose dbPurpose) {
        if(dbPurpose.getFileIds()==null||dbPurpose.getFileIds().isEmpty()){
            this.save(dbPurpose);
        }else {
            dbPurpose.setFileGroupId(null);
            this.save(dbPurpose);
            UpdateWrapper<DbPurpose> dbPurposeUpdateWrapper = new UpdateWrapper<>();
            String fileGroupId = "db_purpose"+dbPurpose.getId();
            dbPurposeUpdateWrapper.set("file_group_id",fileGroupId).in("id",dbPurpose.getId());
            this.update(dbPurpose,dbPurposeUpdateWrapper);
            UpdateWrapper<DbFile> updateWrapper = new UpdateWrapper<>();
            DbFile dbFile = new DbFile();
            updateWrapper.set("group_id", fileGroupId).in("id",dbPurpose.getFileIds());
            dbFileService.update(dbFile,updateWrapper);
        }
    }
    /**
     * 更新文件信息
     * @param dbPurpose
     */
    @Transactional
    public void updateAndFileById(DbPurpose dbPurpose) {
        if(dbPurpose.getFileIds()==null||dbPurpose.getFileIds().isEmpty()){
            this.updateById(dbPurpose);
        }else {
            dbPurpose.setFileGroupId(null);
            this.updateById(dbPurpose);
            UpdateWrapper<DbPurpose> dbPurposeUpdateWrapper = new UpdateWrapper<>();
            String fileGroupId = "db_purpose"+dbPurpose.getId();
            dbPurposeUpdateWrapper.set("file_group_id",fileGroupId).in("id",dbPurpose.getId());
            this.update(dbPurpose,dbPurposeUpdateWrapper);
            UpdateWrapper<DbFile> updateWrapper = new UpdateWrapper<>();
            DbFile dbFile = new DbFile();
            updateWrapper.set("group_id", fileGroupId).in("id",dbPurpose.getFileIds());
            dbFileService.update(dbFile,updateWrapper);
        }
    }
    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @Transactional
    public void deleteById(String id) {
        //删除文件
        DbPurpose dbPurpose = this.getById(id);
        if(dbPurpose.getFileGroupId()!=null){
            QueryWrapper<DbFile> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("group_id",dbPurpose.getFileGroupId());
            List<DbFile> list = dbFileService.list(queryWrapper);
            list.forEach(dbFile -> {
                dbFileService.removeById(dbFile.getId());
            });
        }
        this.removeById(id);
    }

    @Transactional
    public void deleteBatch(String ids) {
        //批量删除文件
        List<String> idList= Arrays.asList(ids.split(","));
        idList.forEach(id -> {
            DbPurpose dbPurpose = this.getById(id);
            if(dbPurpose.getFileGroupId()!=null){
                QueryWrapper<DbFile> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("group_id",dbPurpose.getFileGroupId());
                List<DbFile> list = dbFileService.list(queryWrapper);
                list.forEach(dbFile -> {
                    dbFileService.removeById(dbFile.getId());
                });
            }
        });
        this.removeByIds(idList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    public DbPurposeVo queryById(String id) {
        DbPurpose dbPurpose = this.getById(id);
        if(dbPurpose==null) {
            return null;
        }
        DbPurposeVo dbPurposeVo = new DbPurposeVo();
        QueryWrapper<DbFile> queryWrapper = new QueryWrapper<>();
        BeanUtils.copyProperties(dbPurpose,dbPurposeVo);
        //查找文件路径和id
        if(dbPurpose.getFileGroupId()!=null){
            queryWrapper.eq("group_id",dbPurpose.getFileGroupId());
            List<DbFile> list = dbFileService.list(queryWrapper);
            List<String> dbFileList = new ArrayList<>();
            List<String> dbFileIds = new ArrayList<>();
            list.forEach(dbFile -> {
                dbFileList.add(dbFile.getFilePath());
                dbFileIds.add(dbFile.getId());
            });
            dbPurposeVo.setFilePaths(dbFileList);
            dbPurposeVo.setFileIds(dbFileIds);
        }
        return dbPurposeVo;
    }

    /**
     * 意向统计
     * @return
     */
    @Override
    public PurposeStatisticsVo purposeStatistics() {
//       统计商机总数
        Long total = dbPurposeMapper.selectCount(Wrappers.emptyWrapper());
//        统计本月新增
        QueryWrapper<DbPurpose> wrapper = new QueryWrapper<>();
        LocalDate now = LocalDate.now();
        // 获取当前月份的第一天（月初）
        LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
        // 获取当前月份的最后一天（月底）
        LocalDate lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());
        wrapper.ge("create_time",firstDayOfMonth)
                .le("create_time",lastDayOfMonth);
        Long increase = dbPurposeMapper.selectCount(wrapper);
        LocalDate localDate = now.minusDays(30);
//        查询所有customerId
        List<DbPurpose> dbPurposes = dbPurposeMapper.selectList(Wrappers.emptyWrapper());
        List<String > ids = null;
        if(CollectionUtils.isNotEmpty(dbPurposes)){
            ids = dbPurposes.stream()
                    .map(dbPurpose -> dbPurpose.getId())
                    .collect(Collectors.toList());
        }
        LambdaQueryWrapper<DbPurposeFollowUp> wrappers = Wrappers.<DbPurposeFollowUp>lambdaQuery().in(DbPurposeFollowUp::getPurId, ids)
                .orderByDesc(DbPurposeFollowUp::getDate)
                .last("LIMIT 1");
        List<DbPurposeFollowUp> dbPurposeFollowUpList = dbPurposeFollowUpService.list(wrappers);
        List<DbPurposeFollowUp> ups = null;
        if(CollectionUtils.isNotEmpty(dbPurposeFollowUpList)){
            ups = dbPurposeFollowUpList.stream()
                    .filter(dbPurposeFollowUp -> dbPurposeFollowUp.getDate().isBefore(localDate))
                    .collect(Collectors.toList());
        }
        long followUp = ups.stream().count();
        return PurposeStatisticsVo.builder().total(total).increase(increase).followUp(followUp).build();
    }

}
